//
//  CLRemakeView.m
//  MasonryTest
//
//  Created by Charles on 16/9/23.
//  Copyright © 2016年 Charles. All rights reserved.
//

#import "CLRemakeView.h"

@interface CLRemakeView()

@property (nonatomic, strong) UIButton *movingButton;
@property (nonatomic, assign) BOOL topLeft;

- (void)toggleButtonPosition;
@end

@implementation CLRemakeView

- (instancetype)init{
    if (self = [super init]) {
        [self makeView];
    }
    return self;
}

- (void)makeView{

    [self.movingButton setTitle:@"Move Me!" forState:UIControlStateNormal];
    self.movingButton.layer.borderColor = UIColor.greenColor.CGColor;
    self.movingButton.layer.borderWidth = 3;
    [self.movingButton addTarget:self action:@selector(toggleButtonPosition) forControlEvents:UIControlEventTouchUpInside];
    self.topLeft = YES;
}

- (UIButton *)movingButton{
    if (!_movingButton) {
        _movingButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self addSubview:_movingButton];
    }
    return _movingButton;
}

+ (BOOL)requiresConstraintBasedLayout{
    return YES;
}

- (void)updateConstraints{
    
    [self.movingButton remakeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(100));
        make.height.equalTo(@(100));
        
        if (self.topLeft) {
            make.left.equalTo(self.left).with.offset(10);
            make.top.equalTo(self.top).with.offset(10);
        }else{
            make.bottom.equalTo(self.bottom).with.offset(-10);
            make.right.equalTo(self.right).with.offset(-10);
        }
    }];
    [super updateConstraints];
}

- (void)toggleButtonPosition{
    self.topLeft = !self.topLeft;
    
    [self setNeedsUpdateConstraints];

    [self updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.35 animations:^{
        [self layoutIfNeeded];
    }];
}


@end
